from decimal import ROUND_HALF_UP, Decimal
from fastapi.concurrency import run_in_threadpool
from config.database import AsyncSessionLocal
from module_task.stock.bollgen import gen_boll_realtime, init_boll_cache
from module_task.stock.macdgen import gen_macd_realtime, init_macd_cache
from utils.ak_util import filter_ak_stock
from utils.log_util import logger
import akshare as ak

async def gen_kline_realtime_job(): 
    """
    生成股票的实时指标数据
    1.查询股票基础信息表
    2 
    2.1如果没有数据，说明基础数据表未同步，提示同步基础数据表未同步的错误
    2.2如果有数据，则从akshare查询实时数据，计算实时指标
    :param 
    :return: 
    """
    try:
        async with AsyncSessionLocal() as session:
            #实时行情
            stock_df = await run_in_threadpool(ak.stock_zh_a_spot_em)
            stock_df = filter_ak_stock(stock_df, '代码', '名称')
            transform_colums = ['今开', '最新价', '最高', '最低']

            stock_df[transform_colums] = stock_df[transform_colums].map(
                lambda x: Decimal(str(x)).quantize(Decimal('0.00'), rounding=ROUND_HALF_UP)
            )
            
            # stock_zh_a_spot_em_df = pd.DataFrame([{
            #     "代码" : "000001",
            #     "最新价" : Decimal(12.99).quantize(Decimal('0.00')),
            #     "最高" : Decimal(13.17).quantize(Decimal('0.00')),
            #     "最低" : Decimal(12.86).quantize(Decimal('0.00')),
            #     "今开": Decimal(12.87).quantize(Decimal('0.00'))
            # }]
            # )
            for row in stock_df.itertuples():
                try :               
                    await gen_macd_realtime(session, row)
                    await gen_boll_realtime(session, row)                     
                except Exception as e:
                    logger.error(e)
    except Exception as e:
        await session.rollback()
        raise e
    
async def gen_indicator_cache_job(): 
    """
    生成股票的实时指标数据所依赖的基础指标数据缓存
    :param 
    :return: 
    """
    try:      
        await init_boll_cache()
        await init_macd_cache()                 
    except Exception as e:
        logger.error(e)
        raise e